package com.itheima.chapter07.service;

import com.itheima.chapter07.domain.Authority;
import com.itheima.chapter07.domain.Customer;
import com.itheima.chapter07.respository.AuthorityRepository;
import com.itheima.chapter07.respository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private AuthorityRepository authorityRepository;
    @Autowired
    private RedisTemplate redisTemplate;

    public Customer getCustomer(String userName) {
        Customer customer = null;
        Object o = redisTemplate.opsForValue().get("Customer_" + userName);
        if (o == null) {
            customer = customerRepository.findByUsername(userName);
            if (customer != null) {
                redisTemplate.opsForValue().set("Customer_" + userName, customer);
            }
        } else {
            customer = (Customer) o;
        }
        return customer;
    }

    public List<Authority> getCustomerAuthority(String userName) {
        List<Authority> authorities = null;
        Object o = redisTemplate.opsForValue().get("authorities_" + userName);
        if (o == null) {
            authorities = authorityRepository.findAuthoritiesByUsername(userName);
            if (authorities != null && authorities.size() > 0) {
                redisTemplate.opsForValue().set("authorities_" + userName, authorities);
            }
        } else {
            authorities = (List<Authority>) o;
        }
        return authorities;
    }
}
